import ArticleItem from '@/components/ArticleItem'
import { getArticleList, getNewestArticleList } from '@/store/actions/home'
import { RootState } from '@/types/store'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'

type Props = {
  channelId: number
}
const ArticleList = ({ channelId }: Props) => {
  // const [data, setData] = useState<string[]>([])
  const dispatch = useDispatch()
  const history = useHistory()
  const { channelActicles } = useSelector((state: RootState) => state.home)
  const { pre_timestamp, results = [] } = channelActicles[channelId] ?? {
    pre_timestamp: Date.now() + '',
    results: [],
  }
  // console.log(results)
  //下拉加载数据
  const loadMore = async () => {
    await dispatch(getArticleList(channelId, pre_timestamp || Date.now() + ''))
  }
  const hasMora = pre_timestamp !== null
  //上拉刷新数据
  const onRefresh = async () => {
    await dispatch(getNewestArticleList(channelId, new Date() + ''))
  }
  return (
    <div className={styles.root}>
      <PullToRefresh onRefresh={onRefresh}>
        {/* 文章列表中的每一项 */}
        {results.map((item, index) => {
          const {
            art_id,
            title,
            aut_name,
            comm_count,
            pubdate,
            cover: { type, images },
          } = item
          const articleData = {
            title,
            aut_name,
            comm_count,
            pubdate,
            type,
            images,
          }
          return (
            <div
              className="article-item"
              onClick={() => history.push(`/articles/${art_id}`)}
              key={index}
            >
              <ArticleItem {...articleData} />
            </div>
          )
        })}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMora} />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
